import * as childProcess from 'child_process';
const config = require('../../config');

export default class FileService {

  public static async convertFile(filePath, fileName) {
    console.log('start convert');
    await this.runCmdFile(
      config.audiveris_bin,
      [
        '-batch',
        '-export',
        '-output',
        config.output_path,
        '-option',
        'org.audiveris.omr.text.Language.defaultSpecification=eng+chi_sim',
        filePath
      ]
    );
    console.log('end convert');
  }

  public static async runCmdFile(cmdFile, params = [], workDir = null) {
    return new Promise((resolve, reject) => {
      childProcess.execFile(cmdFile, params, {
        cwd: workDir, timeout: 0,
        maxBuffer: 100 * 1024 * 1024
      }, (err, stdout, stderr) => {
        if (err) {
          const msg = `Error occurred \n` +
            `error: ${err} \n` +
            `stdout: ${stdout} \n` +
            `stderr: ${stderr}`;
          reject(msg);
        } else {
          console.log(stdout);
          resolve();
        }
      });
    });
  }
}
